package com.sino.dataworks.util;


import com.aliyuncs.utils.StringUtils;
import com.sino.dataworks.dto.SyncDataStats;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class LogParserUtil {
    public static SyncDataStats parseLog(String logFile) {
        SyncDataStats stats = new SyncDataStats();
        if(StringUtils.isEmpty(logFile)){
            return null;
        }
        if(logFile.equals("没有产生日志信息")){
            return null;
        }
        String[] lines=logFile.split("\n");
            for (String line:lines ) {
                if (line.contains("State: 0(SUCCESS)")) {
                    String[] datas=line.trim().split("\\|");
                    for (String str:datas){
                        if(str.contains("Total")){
                           String[] total=str.split("\\s+");
                           stats.setTotalSize(total[total.length-1]);
                           stats.setTotalRecords(total[total.length-2].replace("R",""));
                        }
                        if(str.contains("Dirty data")){
                            String[]  dirty=str.split("\\s+");
                            stats.setDirtySize(dirty[dirty.length-1]);
                            stats.setDirtyRecords(dirty[dirty.length-2].replace("R",""));
                        }
                    }
                    break;
//                    Pattern pattern = Pattern.compile(
//                            "(?=.*Total:\\s*(\\d+)R\\s+([\\d.]+)([A-Za-z]{2}))" +  // 正向预查Total
//                                    "(?=.*(Dirty data:\\s*(\\d+)R\\s+([\\d.]+)([A-Za-z]{2})))?" + // 可选脏数据
//                                    "^.*$"
//                            ,Pattern.DOTALL);
//                    if (matcher.find()) {
//                        // 提取总数据量
//                        stats.setTotalRecords(Integer.parseInt(matcher.group(1)));
//                        stats.setTotalSize(matcher.group(2)+matcher.group(3).toUpperCase());
//                        // 提取脏数据（如果存在）
//                        int dirtyRecords = 0;
//                        String dirtyDataSizeValue ="0";
//                        String dirtyDataSizeUnit = "B"; // 默认单位
//                        if (matcher.group(4) != null) {
//                            dirtyRecords = Integer.parseInt(matcher.group(5));
//                            dirtyDataSizeValue =matcher.group(6);
//                            dirtyDataSizeUnit = matcher.group(7).toUpperCase();
//                            stats.setDirtyRecords(dirtyRecords);
//                            stats.setDirtySize(dirtyDataSizeValue+dirtyDataSizeUnit);
//                        }
//                    }
                }
            }
        return stats;
    }
    public static String getlogErrorInfo(String errorLog){
        String errorDescription="";
        if(StringUtils.isEmpty(errorLog)){
            log.info("错误日志信息为空");
            return errorDescription;
        }
        Pattern pattern = Pattern.compile("FAILED: .*? - (.*)");
        Matcher matcher = pattern.matcher(errorLog);
        if(matcher.find()) {
             errorDescription = matcher.group(1);
        }
        if(StringUtils.isEmpty(errorDescription)) {
//            Pattern errorPattern = Pattern.compile(
//                    "ErrorMessage:\\nCode:\\[(.*?)\\], Description:\\[(.*?)\\].*?" +
//                            "执行的SQL为:(.*?)具体错误信息为：(.*?)\\n",
//                    Pattern.DOTALL);
//            Pattern errorPattern = Pattern.compile(
//                    "Code:\\[(.*?)\\], Description:\\[(.*?)\\].*?ERROR: (.*?)(?=\\n|$)",
//                    Pattern.DOTALL
//            );
            Pattern errorPattern = Pattern.compile(
                    "Code:\\[(.*?)\\],\\s*Description:\\[(.*?)\\].*?" +
                            "(?:ERROR:\\s*(.*?)|具体错误信息为：(.*?))(?=\\n|$)",
                    Pattern.DOTALL
            );
             matcher = errorPattern.matcher(errorLog);
            if (matcher.find()) {
                log.info("Error Code: " + matcher.group(1));
                log.info("Error Description: " + matcher.group(2));
              //  log.info("Specific Error: " + matcher.group(4).trim());
//                if(matcher.group(2)!=null){
//                    errorDescription=matcher.group(2);
//                }
                if(matcher.group(3)!=null){
                    log.info("ERROR: " + matcher.group(3).trim());
                    errorDescription=matcher.group(3);
                }
                if(matcher.group(4)!=null){
                    log.info("ERROR: " + matcher.group(4).trim());
                    errorDescription=matcher.group(4);
                }
            }
            if(StringUtils.isEmpty(errorDescription)){
                Pattern detailPattern = Pattern.compile("Code:\\[(.*?)\\], Description:\\[(.*?)\\].*errorMessage: (.*)");
                matcher = detailPattern.matcher(errorLog);
                if (matcher.find()) {
                    log.info("=== 提取到的错误详细信息 ===");
                    log.info("错误代码: " + matcher.group(1));
                    log.info("错误描述: " + matcher.group(2));
                    log.info("错误消息: " + matcher.group(3));
                    if(matcher.group(3)!=null){
                        errorDescription=matcher.group(3);
                    }
                }
            }
            if(errorLog.contains("任务并发执行数已达上限")){
                errorDescription=errorLog;
            }
            if(StringUtils.isEmpty(errorDescription)){
                errorDescription=extractErrorMessages(errorLog);
                log.info(errorDescription);
            }
            if(StringUtils.isEmpty(errorDescription)){
                 pattern = Pattern.compile("Caused by:\\s+(.*)");
                 matcher = pattern.matcher(errorLog);
                 if(matcher.find()){
                     errorDescription=matcher.group(1).trim();
                 }
            }
            if(StringUtils.isEmpty(errorDescription)){
                pattern = Pattern.compile("java.sql.SQLIntegrityConstraintViolationException:\\s+(.*)");
                matcher = pattern.matcher(errorLog);
                if(matcher.find()){
                    errorDescription=matcher.group(1).trim();
                }
            }
            if(StringUtils.isEmpty(errorDescription)){
                pattern = Pattern.compile("com.alibaba.datax.common.exception.DataXException:\\s+(.*)");
                matcher = pattern.matcher(errorLog);
                if(matcher.find()){
                    errorDescription=matcher.group(1).trim();
                }
            }
            if(StringUtils.isEmpty(errorDescription)){
                pattern = Pattern.compile("ERROR:pyodps.pyodpswrapper:Got killed");
                matcher = pattern.matcher(errorLog);
                if(matcher.find()){
                    errorDescription="ERROR:pyodps.pyodpswrapper:Got killed:很有可能因为 Out of memory";
                }
            }
        }
        return errorDescription.replace("ERROR:","").trim();
    }
    /**
     * 提取错误描述（排除 ODPS- 错误代码）
     * @param log 原始日志文本
     * @return 纯错误描述列表
     */
    public static String extractErrorMessages(String log) {
        String errorMessages ="";
        // 匹配 ODPS- 错误代码及后续描述
        Pattern pattern  =  Pattern.compile("ODPS-\\d+:.*?(?=\\n|$)");
        Matcher matcher = pattern.matcher(log);

        if (matcher.find()) {
            String message = matcher.group().trim();
             errorMessages = message.replaceFirst("ODPS-\\d+:", "");
        }
        return errorMessages;
    }

}
